<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/18
 * Time: 10:48
 */

namespace app\domain;
use app\server\gasStation as modelGasStation;
use app\server\request as modelRE;
use rap\config\Config;

class gasStation
{

    public function getGasStation ($lon, $lat, $where, $field = "*") {

        $sql = "SELECT $field,ROUND(6370.996 * 2 * ASIN(SQRT( POW(SIN(($lat * PI() / 180 - lat * PI() / 180) / 2), 2) + COS($lat * PI() / 180) * COS(lat * PI() / 180) * POW(
                    SIN(($lon * PI() / 180 - lon * PI() / 180) / 2),2)) ) * 1000) /1000 AS distance FROM mp_gas_station WHERE (isdelete=0) ORDER BY distance ASC, create_time DESC";
        $list =  modelGasStation::getGasStationList($sql);
        



        return $list;

    }

    public function getGasStationList($page = 1, $lat, $lon, $round = 3000) {

        $config = Config::getFileConfig();
        $where = [
            'page' => $page,
            'lat' => $lat,
            'lon' => $lon,
            'r' => $round,
            'key' => $config['gasStation']['key'],
        ];

        $list = modelRE::getMethod($config['gasStation']['dis_url'], $where);
//        $list = $_SESSION['list'];
        if ($list['resultcode'] == 200){
            $data = [];
            $list = $list['result']['data'];
            for ($i = 0; $i < count($list); $i++) {
                $data[$i]['id'] = $list[$i]['id'];
                $data[$i]['station_name'] = $list[$i]['name'];
                $data[$i]['address'] = $list[$i]['address'];
                $data[$i]['lat'] = $list[$i]['lat'];
                $data[$i]['lon'] = $list[$i]['lon'];
                $data[$i]['price_92'] = $list[$i]['price']['E93'];
                $data[$i]['price_95'] = $list[$i]['price']['E97'];
                $data[$i]['distance'] = $list[$i]['distance'] / 1000;
            }

        } else{
         $data = [];
        }
        return $data;

    }

    /**
     * 计算两点地理坐标之间的距离
     * @param Decimal $longitude1 起点经度
     * @param Decimal $latitude1 起点纬度
     * @param Decimal $longitude2 终点经度
     * @param Decimal $latitude2 终点纬度
     * @param Int   $unit    单位 1:米 2:公里
     * @param Int   $decimal  精度 保留小数位数
     * @return Decimal
     */
    function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=2, $decimal=2){

        $EARTH_RADIUS = 6370.996; // 地球半径系数
        $PI = 3.1415926;

        $radLat1 = $latitude1 * $PI / 180.0;
        $radLat2 = $latitude2 * $PI / 180.0;

        $radLng1 = $longitude1 * $PI / 180.0;
        $radLng2 = $longitude2 * $PI /180.0;

        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;

        $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
        $distance = $distance * $EARTH_RADIUS * 1000;

        if($unit==2){
            $distance = $distance / 1000;
        }

        return round($distance, $decimal);

    }
}